/**
 * 获取最近的点
 */
getNearestPoint(linestring, coordinate) {
	// console.log(linestring.getCoordinates(), coordinate);
	let minDistance = Infinity;
	let minCoordinates = null;
	let minIndex = 0;
	linestring.getCoordinates().map((lcoordinate, i) => {
		const line = new LineString([lcoordinate, coordinate]);
		const distance = getLength(line, {
			projection: "EPSG:4326",
		});
		if (minDistance > distance) {
			minDistance = distance;
			minCoordinates = lcoordinate;
			minIndex = i;
		}
	});
	let f = new Feature({
		type: "Point",
		geometry: new Point(minCoordinates),
		name: minIndex,
	});
	f.setStyle(this.pstyle);
	return f;
},
/**
 * 添加点
 * point:Feature
 */
addPoint(point) {
	if (this.hasStart && !this.hasEnd) {
		// 开始且没结束
		if (this.endPoint && this.endPoint.get("name") !== point.get("name")) {
			this.endPoint = null;
		}
		this.$nextTick(() => {
			this.endPoint = point;
		});
	} else if (!this.hasEnd) {
		// 没结束
		if (this.startPoint && this.startPoint.get("name") !== point.get("name")) {
			this.startPoint = null;
		}
		this.$nextTick(() => {
			this.startPoint = point;
		});
	}
},
/**
 * 确认起点
 */
handleStartPoint() {
	this.hasStart = true;
	// 日志输出
	this.fnOutShowResultLogs({ title: "等距标点", content: `确定起始标点` });
},
/**
 * 确定为终点
 */
handleEndPoint() {
	// 未结束
	this.hasEnd = true;
	// 打开节点信息弹出框
	this.dialogVisible = true;

	const geom = this.getSplitGeom();

	const length = getLength(geom, {
		projection: "EPSG:4326",
	});
	this.distance = length.toFixed(2);
	// 日志输出
	this.fnOutShowResultLogs({ title: "等距标点", content: `确定终点标点` });
},
/**
 * 重新开始标点
 */
restartSplitLine() {
	// 想上一个选中feature 恢复常态
	if (!this.hasStartSplitLine && this.activeSplitLineFeature) this.activeSplitLineFeature.feature.setStyle(this.style);
	// 标点 显示信息
	this.showInfoFeature = null;
	// 设置属性值弹出框
	this.dialogVisible = false;
	// 是否结束
	this.hasEnd = false;
	// 是否开始
	this.hasStart = false;
	// 开始点
	this.startPoint = null;
	// 结束点
	this.endPoint = null;
	// 日志输出
	// this.fnOutShowResultLogs({ title: "等距标点", content: `准备就绪，开始等距标点` });
},
/**
 * 取消操作
 * 测距终点
 */
handleCancel() {
	// 关闭等距标点 为选中线条 下一次标点做准备
	this.hasStartSplitLine = false;
	// 重新开始等距标点
	this.restartSplitLine();
	// 终止选中激活线
	this.activeSplitLineFeature = null;
	// 日志输出
	this.fnOutShowResultLogs({ title: "等距标点", content: `取消标点` });
},
handleSubmit() {
	// 日志输出
	this.fnOutShowResultLogs({ title: "等距标点", content: `确认等距标点绘制属性信息` });
	// const fill = this.style.getImage().getFill();
	// fill.setColor(this.stroke_color);
	// this.style.getImage().setFill(fill);
	this.dialogVisible = false;
	this.handleSplitLine();
},
/**
 * 获取激活feature 中 需要分割的部分或全部feature
 */
getSplitGeom() {
	this.hasEnd = true;
	let linestring = this.activeSplitLineFeature.feature.getGeometry().clone();
	let startIndex = +this.startPoint.get("name");
	let endIndex = +this.endPoint.get("name");
	if (startIndex > endIndex) {
		[startIndex, endIndex] = [endIndex, startIndex];
	}
	let coordinates = linestring.getCoordinates();
	coordinates = coordinates.slice(startIndex, endIndex + 1);
	linestring.setCoordinates(coordinates);
	// 日志输出
	this.fnOutShowResultLogs({ title: "等距标点", content: `计算线Feature Geometry 数据` });
	return linestring;
},
/**
 * 根据提取的元素
 * 按照设置段落进行分割
 */
handleSplitLine() {
	//轨迹线图形
	let line = this.getSplitGeom();
	// console.log('🚀 ~ file: OptionLine.vue:505 ~ split ~ line:', line);
	// 地图分辨率
	// let res = this.map.getView().getResolution();
	// console.log("🚀 ~ file: OptionLine.vue:492 ~ split ~ res:", res)
	//轨迹地理长度
	// let length = line.getLength();
	//像素间隔步长
	let stpes = this.splitFeatureVal; //像素步长间隔
	//将像素步长转实际地理距离步长
	// let geo_steps = stpes * res;
	//箭头总数
	let num = parseInt(stpes);
	let splitPointFeatures = [];
	let properties = this.activeSplitLineFeature.feature.get("properties");
	for (let i = 0; i < num; i++) {
		// 返回沿线串提供的分数处的坐标，分数是 0 到 1 之间的数字，其中 0 是线串的开头，1 是结束
		let point = line.getCoordinateAt((i * 1.0) / (num - 1));
		let feature = new Feature({
			type: "Point",
			geometry: new Point(point),
			name: "split_point_" + i,
			properties: {
				id: i,
				layer_id: properties.layer_id,
				line_id: properties.id,
			},
		});
		splitPointFeatures.push(feature);
	}
	// 当前线切割点 集合
	this.currentLineFeatureSplitPointArr = splitPointFeatures;
	this.startPoint = null;
	this.endPoint = null;
	this.dialogLayersVisible = true;
	// 日志输出
	this.fnOutShowResultLogs({ title: "等距标点", content: `等距标点计算完成` });
	// this.hasStart = false;
	// this.hasEnd = false;
	console.log("🚀 ~ file: index.vue:1934 ~ split ~ this.features:", this.features);
},
/**
 * 提交
 * 切割点指定图层
 */
handleSubmitSplitPointSaveLayer() {
	// 日志输出
	this.fnOutShowResultLogs({ title: "等距标点", content: `标点保存到元图层中...` });
	// this.splitPointToLayerId
	// console.log('🚀 ~ file: index.vue:2143 ~ handleSubmitSplitPointSaveLayer ~ this.splitPointToLayerId:', this.splitPointToLayerId);
	// this.dialogLayersVisible = false;
	if (!this.splitPointToLayerId) {
		this.$message("未找到要保存的图层！");
		return false;
	}
	let currentLineFeatureSplitPointArr = this.currentLineFeatureSplitPointArr;
	let targetLayer = this.layers.find(layer => layer.layerId == this.splitPointToLayerId);
	let properties = targetLayer.properties;
	let featureList = currentLineFeatureSplitPointArr.map(feature => {
		const featureGeoJSON = new GeoJSON().writeFeatureObject(feature);
		return {
			featureValue: JSON.stringify(featureGeoJSON.geometry),
			extField: properties.extField,
			propValue1: properties.propValue1,
			propValue2: properties.propValue2,
			styleValue1: properties.styleValue1,
			styleValue2: properties.styleValue2,
		};
	});
	IAddMetaLayerGeo({
		metaId: this.splitPointToLayerId, //必传项
		featureList: [...featureList],
	})
		.then(response => {
			// 日志输出
			this.fnOutShowResultLogs({ title: "等距标点", content: `标点存储成功` });
			this.dialogLayersVisible = false;
			this.$message.success("更新成功");
			this.features = [...this.features, ...currentLineFeatureSplitPointArr];
			this.$nextTick(() => {
				// 日志输出
				this.fnOutShowResultLogs({ title: "等距标点", content: `标点绘制完成` });
				// 关闭等距标点 为选中线条 下一次标点做准备
				this.hasStartSplitLine = false;
				// 重新开始等距标点
				this.restartSplitLine();
				// 终止选中激活线
				this.activeSplitLineFeature = null;
			});
			// 重新加载主图层
			// this.toolResetLayer();
		})
		.catch(() => {
			this.$message({
				type: "info",
				message: "已取消删除",
			});
			// 日志输出
			this.fnOutShowResultLogs({ title: "等距标点", content: `标点存储失败` });
		});
},
/**
 * 取消
 * 切割点指定图层
 */
handleCancelSplitPointSaveLayer() {
	this.fnOutShowResultLogs({ title: "等距标点", content: `取消标点数据库存储` });
	this.features = [...this.features, ...this.currentLineFeatureSplitPointArr];
	this.dialogLayersVisible = false;
	this.$nextTick(() => {
		// 日志输出
		this.fnOutShowResultLogs({ title: "等距标点", content: `标点绘制完成` });
		// 关闭等距标点 为选中线条 下一次标点做准备
		this.hasStartSplitLine = false;
		// 重新开始等距标点
		this.restartSplitLine();
		// 终止选中激活线
		this.activeSplitLineFeature = null;
	});
},

/**
 * 开启等距标点
 */
toolOpenSplitLine() {
	// 关闭其他操作
	this.closeAllSwitchControl();
	// 开启等距标点
	this.splitLineSwitchControl = true;
	// 日志输出
	this.fnOutShowResultLogs({ title: "等距标点", content: `开启等距标点控制` });
	// 准备就绪 开始标点
	this.restartSplitLine();
},
/**
 * 关闭等距标点
 */
toolCloseSplitLine() {
	// 线 恢复常态
	this.activeSplitLineFeature.feature.setStyle(this.style);
	this.activeSplitLineFeature = null;
	// 重置切割状态
	this.restartSplitLine();
	// 关闭其他操作
	this.closeAllSwitchControl();
	// 日志输出
	this.fnOutShowResultLogs({ title: "等距标点", content: `关闭等距标点控制` });
},

/**
 * 获取激活要素
 */
handleSelected(active, unActive) {
	console.log("🚀 ~ file: index.vue:1352 ~ handleSelected ~ unActive:", unActive);
	console.log("🚀 ~ file: index.vue:1352 ~ handleSelected ~ active:", active);
	if (this.splitLineSwitchControl) {
		// 是否已经选定feature
		// if (this.hasStart) return false;
		// 线 恢复常态
		// 未选定切割线 一旦选定 样式不允许在变更
		if (!(this.activeSplitLineFeature && this.activeSplitLineFeature.get("layerId") == active.get("layerId")) && this.selectFeature)
			this.selectFeature.feature.setStyle(this.style);
		if (active) {
			this.selectFeature = active;
			if (active.feature.get("type") === "LineString") {
				// 存在激活feature
				// if (this.activeSplitLineFeature) {
				//     // 线 恢复常态
				//     this.activeSplitLineFeature.feature.setStyle(this.style);
				//     this.activeSplitLineFeature = null;
				// }
				// this.activeSplitLineFeature = active;
				// 线
				// 高亮
				active.feature.setStyle(
					new Style({
						stroke: new StrokeStyle({
							color: "red",
							width: 2,
						}),
					})
				);
				// 日志输出
				this.fnOutShowResultLogs({ title: "等距标点", content: `选中线Feature` });
			}
		} else if (unActive) {
			// 线 恢复常态
			unActive.feature.setStyle(this.style);
			// 日志输出
			this.fnOutShowResultLogs({ title: "等距标点", content: `取消选中线Feature` });
			// this.activeSplitLineFeature = null;
		}
	}
},
/**
 * 鼠标移动
 * MiningMap pointermove
 */
handlePointerMove(evt) {
	// 记录Map 鼠标轨迹
	this.result = {
		title: "当前坐标",
		content: "鼠标位置",
		position: evt.coordinate,
	};
	// 测量
	if (this.measureSwitchControl) {
		if (evt.dragging) {
			return;
		}
		/** @type {string} */
		let helpMsg = "Click to start drawing";

		if (this.sketch) {
			const geom = this.sketch.getGeometry();
			if (geom instanceof Polygon) {
				this.helpMsg = this.continuePolygonMsg;
			} else if (geom instanceof LineString) {
				this.helpMsg = this.continueLineMsg;
			}
		}
		// 右键 继续绘制
		// if(!this.draw) helpMsg = continueMsg;

		this.helpTooltipElement.innerHTML = helpMsg;
		this.helpTooltip.setPosition(evt.coordinate);

		this.helpTooltipElement.classList.remove("hidden");
	}
	// 等距标点
	if (this.hasStartSplitLine) {
		// 存在激活feature
		if (this.activeSplitLineFeature) {
			let linestring = this.activeSplitLineFeature.feature.getGeometry();
			// 判断激活feature 类型 只对 LineString 使用
			if (linestring instanceof LineString) {
				// 获取距离线最近的点
				let point = this.getNearestPoint(linestring, evt.coordinate);
				// 添加点
				this.addPoint(point);
			}
		}
	}
},
/**
 * Map 双击
 */
mapDblclick(evt) {
	// 关闭测量
	if (this.measureSwitchControl) {
		// 开始绘制
		// this.startMeasure(this.hasMeasureType);
	}
},
/**
 * Map click
 */
mapClick(evt) {
	console.log("🚀 ~ file: index.vue:1973 ~ mapClick ~ evt:", evt);
	// 开启测量
	if (this.measureSwitchControl) {
	}
	// 等距切割
	if (this.splitLineSwitchControl) {
		// 筛选点击坐标位置hitTolerance: 10 范围 内的的可以操作节点
		let active = this.map.forEachFeatureAtPixel(
			evt.pixel,
			function (feature, layer) {
				return {
					feature: feature,
					layer: layer,
				};
			},
			{
				hitTolerance: 10,
			}
		);
		if (active) {
			// console.log(active.feature);
			let linestring = active.feature.getGeometry();
			if (linestring instanceof LineString) {
				// 将上一个选中feature 恢复常态
				if (this.activeSplitLineFeature) this.activeSplitLineFeature.feature.setStyle(this.style);
				// 线
				// 高亮
				active.feature.setStyle(
					new Style({
						stroke: new StrokeStyle({
							color: "orange",
							width: 2,
						}),
					})
				);
				this.activeSplitLineFeature = active;
			}
		}
	}
},